package com.tango.tangoapp.arealearning;

/**
 * Created by black on 2017/7/18.
 */

import android.app.Activity;
import android.app.FragmentManager;
import android.content.Intent;
import android.os.Bundle;
import android.view.ContextMenu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;

import com.google.atap.tangoservice.Tango;

import com.google.atap.tangoservice.TangoAreaDescriptionMetaData;
import com.google.atap.tangoservice.TangoErrorException;
import com.tango.tangoapp.R;

import java.util.ArrayList;

/**
 * Manage ADF.
 */
public class AdfUuidListViewActivity extends Activity implements SetAdfNameDialog.CallbackListener{
    private ListView mTangoSpaceAdfListView;
    private AdfUuidArrayAdapter mTangoSpaceAdfListAdapter;
    private ArrayList<AdfData> mTangoSpaceAdfDataList;
    private String[] mTangoSpaceMenuStrings;
    private Tango mTango;
    private volatile boolean mIsTangoReady=false;

    @Override
    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);

        setContentView(R.layout.uuid_list_view);
        mTangoSpaceMenuStrings=getResources().getStringArray(
                R.array.set_dialog_menu_items_api_space);

        mTangoSpaceAdfListView=(ListView)findViewById(R.id.uuid_list_view_tango_space);
        mTangoSpaceAdfDataList=new ArrayList<AdfData>();
        mTangoSpaceAdfListAdapter=new AdfUuidArrayAdapter(this,mTangoSpaceAdfDataList);
        mTangoSpaceAdfListView.setAdapter(mTangoSpaceAdfListAdapter);
        registerForContextMenu(mTangoSpaceAdfListView);
    }

    @Override
    public void onResume(){
        super.onResume();
        mTango=new Tango(AdfUuidListViewActivity.this, new Runnable() {
            @Override
            public void run() {
                mIsTangoReady=true;
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        synchronized (AdfUuidListViewActivity.this){
                            updateList();
                        }
                    }
                });
            }
        });
    }

    @Override
    public void onPause(){
        super.onPause();
        synchronized (this){
            mTango.disconnect();
        }
        mIsTangoReady=false;
    }

    @Override
    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
        AdapterView.AdapterContextMenuInfo info=(AdapterView.AdapterContextMenuInfo) menuInfo;
        if(v.getId()==R.id.uuid_list_view_tango_space) {
            menu.setHeaderTitle(mTangoSpaceAdfDataList.get(info.position).uuid);
            menu.add(mTangoSpaceMenuStrings[0]);
            menu.add(mTangoSpaceMenuStrings[1]);
        }
    }

    @Override
    public boolean onContextItemSelected(MenuItem item){
        if(!mIsTangoReady){
            Toast.makeText(this,R.string.tango_not_ready,Toast.LENGTH_SHORT).show();
            return false;
        }
        AdapterView.AdapterContextMenuInfo info=
                (AdapterView.AdapterContextMenuInfo)item.getMenuInfo();
        String itemName=(String)item.getTitle();
        int index=info.position;

        if(itemName.equals(mTangoSpaceMenuStrings[0])){
            showSetNameDialog(mTangoSpaceAdfDataList.get(index).uuid);
        }else if (itemName.equals(mTangoSpaceMenuStrings[1])){
            deleteAdfFromTangoSpace(mTangoSpaceAdfDataList.get(index).uuid);
        }

        updateList();
        return true;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data){
        if(requestCode==Tango.TANGO_INTENT_ACTIVITYCODE){
            if (resultCode==RESULT_CANCELED){
                Toast.makeText(this,R.string.no_permissions,Toast.LENGTH_LONG).show();
            }
        }
        updateList();
    }

    @Override
    public void onAdfNameOk(String name,String uuid){
        if (!mIsTangoReady){
            Toast.makeText(this,R.string.tango_not_ready,Toast.LENGTH_SHORT).show();
            return;
        }
        TangoAreaDescriptionMetaData metadata;
        metadata=mTango.loadAreaDescriptionMetaData(uuid);
        byte[] adfNameBytes=metadata.get(TangoAreaDescriptionMetaData.KEY_NAME);
        if(adfNameBytes!=name.getBytes()){
            metadata.set(TangoAreaDescriptionMetaData.KEY_NAME,name.getBytes());
        }
        mTango.saveAreaDescriptionMetadata(uuid,metadata);
        updateList();
    }

    @Override
    public void onAdfNameCancelled(){

    }

    public void deleteAdfFromTangoSpace(String uuid){
        try {
            mTango.deleteAreaDescription(uuid);
        }catch (TangoErrorException e){
            Toast.makeText(this,R.string.no_uuid_tango_error,Toast.LENGTH_SHORT).show();
        }
    }

    private void updateTangoSpaceAdfList(){
        ArrayList<String> fullUuidList;
        TangoAreaDescriptionMetaData metadata=new TangoAreaDescriptionMetaData();

        try{
            fullUuidList=mTango.listAreaDescriptions();
            mTangoSpaceAdfDataList.clear();
            for(String uuid:fullUuidList){
                String name;
                try{
                    metadata=mTango.loadAreaDescriptionMetaData(uuid);
                }catch (TangoErrorException e){
                    Toast.makeText(this,R.string.exception_tango_error,Toast.LENGTH_SHORT).show();
                }
                name=new String(metadata.get(TangoAreaDescriptionMetaData.KEY_NAME));
                mTangoSpaceAdfDataList.add(new AdfData(uuid,name));
            }
        }catch (TangoErrorException e){
            Toast.makeText(this,R.string.exception_tango_error,Toast.LENGTH_SHORT).show();
        }
    }

    private void updateList(){
        updateTangoSpaceAdfList();
        mTangoSpaceAdfListAdapter.setAdfData(mTangoSpaceAdfDataList);
        mTangoSpaceAdfListAdapter.notifyDataSetChanged();
    }

    private void showSetNameDialog(String mCurrentUuid){
        if(!mIsTangoReady){
            Toast.makeText(this,R.string.tango_not_ready,Toast.LENGTH_SHORT).show();
            return;
        }
        Bundle bundle=new Bundle();
        TangoAreaDescriptionMetaData metadata=mTango.loadAreaDescriptionMetaData(mCurrentUuid);
        byte[] adfNameBytes=metadata.get(TangoAreaDescriptionMetaData.KEY_NAME);
        if(adfNameBytes!=null){
            String fillDialogName=new String(adfNameBytes);
            bundle.putString(TangoAreaDescriptionMetaData.KEY_NAME,fillDialogName);
        }
        bundle.putString(TangoAreaDescriptionMetaData.KEY_UUID,mCurrentUuid);
        FragmentManager manager=getFragmentManager();
        SetAdfNameDialog setAdfNameDialog=new SetAdfNameDialog();
        setAdfNameDialog.setArguments(bundle);
        setAdfNameDialog.show(manager,"ADFNameDialog");
    }

}
